<script setup>
import { ref, onMounted, computed } from 'vue'
import Dialog_visible_service from "./dialog_visible_service.vue";
import {router} from "../router/index.js";
import { ElMessage,ElMessageBox } from 'element-plus'
import axios from "axios";
import {
  User,
  Clock,
  Check,
  Close,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()

// 页面数据
const serviceData = ref({})

// 状态颜色映射
const statusColors = {
  '待审核': 'status-green',
  '已驳回': 'status-red',
  '待服务': 'status-blue',
  '已取消': 'status-grey',
  '已完成': 'status-purple'
}
const getserviceData = () => {
  axios.get(`/contract/selectContractDetail/${route.query.contractId}`).then(res => {
    serviceData.value = res.data;
  })
}
//分辨男女
const GENDER_MAP = {
  1: '男',
  0: '女',
  null: '未知'
};

onMounted(() => {
  getserviceData();
})
//流程图标
// 图标动态计算（保持不变）
const auditIcon = computed(() => {
  switch(serviceData.value.status) {
    case '已驳回': return Close
    case '待审核': return Clock
    default: return Check // 已审核
  }
})

const finalIcon = computed(() => {
  switch(serviceData.value.status) {
    case '已完成': return CircleCheck
    case '已取消': return CircleClose
    default: return Clock // 待服务
  }
})

// 信息文本计算（保持不变）
const auditInfo = computed(() => {
  if (!serviceData.value.auditTime) {
    return serviceData.value.status === '已驳回' ? '已驳回' : '审核中'
  }
  return `${serviceData.value.auditTime} ${serviceData.value.auditName}${
      serviceData.value.status === '已驳回' ? '已驳回' : '已审核'
  }`
})

const finalInfo = computed(() => {
  if (serviceData.value.status === '已完成') {
    return serviceData.value.completionTime
        ? `${serviceData.value.completionTime} ${serviceData.value.doctorName}已服务`
        : '服务中'
  } else if (serviceData.value.status === '已取消') {
    return serviceData.value.cancellationTime
        ? `${serviceData.value.cancellationTime}
         ${serviceData.value.doctorName}已取消`
        : '取消中'
  }
  return '待服务'
})

const showAuditStep = computed(() => {
  // 所有状态都显示审核步骤，除非是未提交状态（如果需要）
  return true;
})

const showFinalStep = computed(() =>
    ['待服务', '已完成', '已取消'].includes(serviceData.value.status)
)

// 连接线显示控制
const showConnector = (step) => {
  if (step === 1) return showAuditStep.value // 现在总是显示
  if (step === 2) return showFinalStep.value
  return false
}

// 修正的标签类型控制：
// 为待审核状态添加warning类型
const getTagType = (step) => {
  const status = serviceData.value.status

  if (step === 'resident') return 'primary'

  if (step === 'audit') {
    if (status === '已驳回') return 'danger'
    if (status === '待审核') return 'warning'
    return 'success' // 已审核
  }

  if (step === 'final') {
    if (status === '待服务') return 'warning'
    return status === '已取消' ? 'danger' : 'success'
  }
}

const residentId = ref(0)
const contractId = ref(0)
//完成服务弹窗
const addDialog = ref(false)
const completedService = () => {
  addDialog.value = true
  residentId.value = serviceData.value.residentId;
  contractId.value = serviceData.value.contractId;
}
const getShowDialog = (val) => {
  addDialog.value = val
  getserviceData();
}
//取消预约弹窗
const cancelDialogVisible = ref(false)
const cancellation =()=>{
  cancelDialogVisible.value = true
  contractId.value = serviceData.value.contractId;
}
const getCancelDialog = (val) => {
  cancelDialogVisible.value = val
  getserviceData();
}
//驳回弹窗
const rejectDialogVisible = ref(false)
const rejectService = () => {
  rejectDialogVisible.value = true
  contractId.value = serviceData.value.contractId;
}
const getRejectDialog = (val) => {
  rejectDialogVisible.value = val
  getserviceData();
}
//编辑服务信息
const edit = () => {
    router.push(`/main/goToApplication?id=${serviceData.value.contractId}`)
  }
const goBack = () => {
  router.go(-1); // 返回上一页，相当于浏览器后退按钮
};
//审核通过
const userName = ref("admin");
const approved = (id) => {
  ElMessageBox.confirm('确定要通过吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {

    axios.put(`/contract/updateApproved/${id}/${userName.value}`).then(res => {
      ElMessage.success(res.data)
      getserviceData();
    })
  }).catch(() => {
    ElMessage.info('已取消')
  })

}
</script>

<template>


      <div class="service-details-container">

        <div class="header-container">
          <!-- 蓝色竖条 -->
          <div class="blue-pillar"></div>

          <!-- 主标题 -->
          <h1 class="service-title">服务详情</h1>

          <!-- 状态印章 -->
          <el-tag :class=" statusColors[serviceData.status]" effect="dark" round  style="border-color: transparent;">{{ serviceData.status }}</el-tag>
          <div class="flow-container">
            <!-- 居民信息 (始终显示) -->
            <div class="flow-step">
              <el-tag  :type="getTagType('resident')" :class="{'always-active': true}"  style="background-color: transparent; border-color: transparent;">
                <el-icon><User /></el-icon>
                {{ serviceData.residentName }}
              </el-tag>
              <div class="connector" v-if="showConnector(1)"></div>
            </div>

            <!-- 审核状态 -->
            <div class="flow-step" v-if="showAuditStep">
              <el-tag :type="getTagType('audit')"  style="background-color: transparent; border-color: transparent;">
                <el-icon :name="auditIcon"></el-icon>
                {{ auditInfo }}
              </el-tag>
              <div class="connector" v-if="showConnector(2)"></div>
            </div>

            <!-- 最终状态 (服务/取消) -->
            <div class="flow-step" v-if="showFinalStep">
              <el-tag :type="getTagType('final')"  style="background-color: transparent; border-color: transparent;">
                <el-icon :name="finalIcon"></el-icon>
                {{ finalInfo }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="section-title">居民信息</div>
        <el-row :gutter="20" :data="serviceData">
          <el-col :span="6">
            <el-form-item label="姓名">
                <span>{{ serviceData.residentName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">
                <span>{{ serviceData.idCard }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="性别">
                <span>{{ GENDER_MAP[serviceData.gender]  }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年龄">
                <span>{{ serviceData.age }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话">
                <span>{{ serviceData.phone }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="现居地">
                <span>{{ serviceData.address }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="居民标签">
              <el-tag
                  v-for="tag in serviceData.tags"
                  :key="tag"
                  :type="tag === '高血压' ? 'danger' : 'success'"
              >
                {{ tag }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="section-title">服务信息</div>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="服务编号">
                <span>{{ serviceData.contractId }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务状态">
                <el-tag :class="statusColors[serviceData.status]">
                  {{ serviceData.status }}
                </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务机构">
                <span>{{ serviceData.institutionName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务团队">
                <span>{{ serviceData.teamName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务医生">
                <span>{{ serviceData.doctorName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务包">
                <span>{{ serviceData.packageName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务项目">
                <span>{{ serviceData.serviceName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务来源">
                <span>{{ serviceData.serviceSource }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务地点">
                <span>{{ serviceData.serviceAddress }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预约时间">
                <span>{{ serviceData.appointmentTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提交时间">
                <span>{{ serviceData.applyTime }}</span>
            </el-form-item>
          </el-col>
          <template v-if="serviceData.status !== '待审核'">
          <el-col :span="8" >
            <el-form-item label="审核时间">
                <span>{{ serviceData.auditTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核人">
                <span>{{ serviceData.auditName }}</span>
            </el-form-item>
          </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="服务备注">
              <span>{{ serviceData.serviceRemark }}</span>
            </el-form-item>
          </el-col>
          <template v-if="serviceData.status === '已驳回'">
          <el-col :span="12">
            <el-form-item label="驳回原因">
                <span>{{ serviceData.rejectionReason }}</span>
            </el-form-item>
          </el-col>
          </template>
          <template v-if="serviceData.status === '已取消'">
            <el-col :span="8" >
              <el-form-item label="取消时间">
                <span>{{ serviceData.cancellationTime }}</span>
              </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="取消原因">
                <span>{{ serviceData.cancellationReason }}</span>
            </el-form-item>
          </el-col>
          </template>
          <template v-if="serviceData.status === '已完成'">
            <el-col :span="8" >
              <el-form-item label="完成时间">
                <span>{{ serviceData.completionTime }}</span>
              </el-form-item>
            </el-col>
          </template>
        </el-row>

        <template v-if="serviceData.status === '已完成'">
          <div class="section-title">健康随访信息</div>
          <el-row :gutter="20" :data="serviceData">
            <el-col :span="8">
              <el-form-item label="血压">
                <span>{{ serviceData.bloodPressure }} mmHg</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="空腹血糖">
                <span>{{ serviceData.fastingBloodGlucose }} mmol/L</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="心率">
                <span>{{ serviceData.heartRate }} 次/分</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="病情描述">
                <span>{{ serviceData.conditionDescription }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="健康指导">
                <span>{{ serviceData.healthGuidance }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <template v-if="serviceData.status === '待审核'">
          <el-button type="primary" @click="edit">编辑服务信息</el-button>
          <el-button type="success" @click="approved(serviceData.contractId)">审核通过</el-button>
          <el-button type="danger" @click="rejectService">驳回</el-button>
          </template>
          <template v-if="serviceData.status === '待服务'">
            <el-button type="primary" @click="edit">编辑服务信息</el-button>
          <el-button type="success" @click="completedService">完成服务</el-button>
          <el-button type="danger" @click="cancellation">取消预约</el-button>
          </template>
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>
  <dialog_visible_service :residentId="residentId" :contractId="contractId" :addDialog="addDialog"  :cancelDialogVisible="cancelDialogVisible" :rejectDialogVisible="rejectDialogVisible"
    @showDialog="getShowDialog" @cancelDialog="getCancelDialog" @rejectDialog="getRejectDialog"/>
</template>

<style scoped>
.header-container {
  position: relative;
  display: flex;
  align-items: center;
  padding: 20px;
  background: #ffffff;
  height: 60px;
}

.blue-pillar {
  border-radius: 15px !important;
  width: 8px;
  height: 28px;
  background: #2984F8;
  margin-right: 12px;
}

.service-title {
  font-size: 20px;
  color: #303133;
  font-weight: 600;
  letter-spacing: 1px;
}


.status-blue {
  color: white;
  background-color: #2984F8;
}
.status-red {
  color: white;
  background-color: #FA746B;
}
.status-green {
  color: white;
  background-color: #3DD4A7;
}
.status-grey {
  color: white;
  background-color: #999999;
}
.status-purple {
  color: white;
  background-color:  #6C76F4;
}

/* 精确尺寸控制 */
:deep(.el-tag) {
  --el-tag-border-radius: 15px;
  --el-tag-font-size: 14px;
}

h3 {
  color: #303133;
  font-size: 16px;
  margin-bottom: 16px;
  font-weight: 600;
}


.family-members div {
  margin-bottom: 8px;
  color: #303133;
}

.action-buttons {
  margin-top: 32px;
  display: flex;
  gap: 16px;
  justify-content: center;
}

.el-tag {
  margin-left: 8px;
  height: 24px;
  line-height: 22px;
}
.service-details-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 20px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  text-align: left;

}

.card-header {
  font-weight: 600;
}

.el-card {
  min-height: 100px;
}
.flow-container {
  display: flex;
  align-items: center;
  padding: 12px 100px;
}

.flow-step {
  display: flex;
  align-items: center;
}

.connector {
  width: 40px;
  height: 2px;
  background-color: #e4e7ed;
  margin: 0 8px;
}

.connector::after {
  content: '→';
  position: absolute;
  right: -12px;
  top: -8px;
  color: #e4e7ed;
}

.el-tag {
  display: inline-flex;
  align-items: center;
  padding: 0 10px;
  height: 28px;
}

.el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.always-active {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-7);
}

/* 不同状态下的连接线颜色 */
.flow-step.success + .flow-step .connector,
.flow-step.success .connector {
  background-color: var(--el-color-success);
}

.flow-step.success + .flow-step .connector::after,
.flow-step.success .connector::after {
  color: var(--el-color-success);
}

.flow-step.danger + .flow-step .connector,
.flow-step.danger .connector {
  background-color: var(--el-color-danger);
}

.flow-step.danger + .flow-step .connector::after,
.flow-step.danger .connector::after {
  color: var(--el-color-danger);
}
</style>